home *** CD-ROM | disk | FTP | other *** search
/ Linux Cubed Series 3: Developer Tools / Linux Cubed Series 3 - Developer Tools.iso / devel / lang / lisp / stk-3.002 / stk-3 / STk-3.1 / Tk / generic / tkSend.c < prev    next >
Encoding:
C/C++ Source or Header  |  1996-05-31  |  53.4 KB  |  1,902 lines

  1. /* 
  2.  * tkSend.c --
  3.  *
  4.  *    This file provides procedures that implement the "send"
  5.  *    command, allowing commands to be passed from interpreter
  6.  *    to interpreter.
  7.  *
  8.  * Copyright (c) 1989-1994 The Regents of the University of California.
  9.  * Copyright (c) 1994-1996 Sun Microsystems, Inc.
  10.  *
  11.  * See the file "license.terms" for information on usage and redistribution
  12.  * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
  13.  *
  14.  * SCCS: @(#) tkSend.c 1.63 96/03/29 12:37:13
  15.  */
  16.  
  17. #include "tkPort.h"
  18. #include "tkInt.h"
  19.  
  20. /* 
  21.  * The following structure is used to keep track of the interpreters
  22.  * registered by this process.
  23.  */
  24.  
  25. typedef struct RegisteredInterp {
  26.     char *name;            /* Interpreter's name (malloc-ed). */
  27.     Tcl_Interp *interp;        /* Interpreter associated with name.  NULL
  28.                  * means that the application was unregistered
  29.                  * or deleted while a send was in progress
  30.                  * to it. */
  31.     TkDisplay *dispPtr;        /* Display for the application.  Needed
  32.                  * because we may need to unregister the
  33.                  * interpreter after its main window has
  34.                  * been deleted. */
  35.     struct RegisteredInterp *nextPtr;
  36.                 /* Next in list of names associated
  37.                  * with interps in this process.
  38.                  * NULL means end of list. */
  39. } RegisteredInterp;
  40.  
  41. static RegisteredInterp *registry = NULL;
  42.                 /* List of all interpreters
  43.                  * registered by this process. */
  44.  
  45. /*
  46.  * A registry of all interpreters for a display is kept in a
  47.  * property "InterpRegistry" on the root window of the display.
  48.  * It is organized as a series of zero or more concatenated strings
  49.  * (in no particular order), each of the form
  50.  *     window space name '\0'
  51.  * where "window" is the hex id of the comm. window to use to talk
  52.  * to an interpreter named "name".
  53.  *
  54.  * When the registry is being manipulated by an application (e.g. to
  55.  * add or remove an entry), it is loaded into memory using a structure
  56.  * of the following type:
  57.  */
  58.  
  59. typedef struct NameRegistry {
  60.     TkDisplay *dispPtr;        /* Display from which the registry was
  61.                  * read. */
  62.     int locked;            /* Non-zero means that the display was
  63.                  * locked when the property was read in. */
  64.     int modified;        /* Non-zero means that the property has
  65.                  * been modified, so it needs to be written
  66.                  * out when the NameRegistry is closed. */
  67.     unsigned long propLength;    /* Length of the property, in bytes. */
  68.     char *property;        /* The contents of the property, or NULL
  69.                  * if none.  See format description above;
  70.                  * this is *not* terminated by the first
  71.                  * null character.  Dynamically allocated. */
  72.     int allocedByX;        /* Non-zero means must free property with
  73.                  * XFree;  zero means use ckfree. */
  74. } NameRegistry;
  75.  
  76. /*
  77.  * When a result is being awaited from a sent command, one of
  78.  * the following structures is present on a list of all outstanding
  79.  * sent commands.  The information in the structure is used to
  80.  * process the result when it arrives.  You're probably wondering
  81.  * how there could ever be multiple outstanding sent commands.
  82.  * This could happen if interpreters invoke each other recursively.
  83.  * It's unlikely, but possible.
  84.  */
  85.  
  86. typedef struct PendingCommand {
  87.     int serial;            /* Serial number expected in
  88.                  * result. */
  89.     TkDisplay *dispPtr;        /* Display being used for communication. */
  90.     char *target;        /* Name of interpreter command is
  91.                  * being sent to. */
  92.     Window commWindow;        /* Target's communication window. */
  93.     Tcl_Interp *interp;        /* Interpreter from which the send
  94.                  * was invoked. */
  95.     int code;            /* Tcl return code for command
  96.                  * will be stored here. */
  97.     char *result;        /* String result for command (malloc'ed),
  98.                  * or NULL. */
  99.     char *errorInfo;        /* Information for "errorInfo" variable,
  100.                  * or NULL (malloc'ed). */
  101.     char *errorCode;        /* Information for "errorCode" variable,
  102.                  * or NULL (malloc'ed). */
  103.     int gotResponse;        /* 1 means a response has been received,
  104.                  * 0 means the command is still outstanding. */
  105.     struct PendingCommand *nextPtr;
  106.                 /* Next in list of all outstanding
  107.                  * commands.  NULL means end of
  108.                  * list. */
  109. } PendingCommand;
  110.  
  111. static PendingCommand *pendingCommands = NULL;
  112.                 /* List of all commands currently
  113.                  * being waited for. */
  114.  
  115. /*
  116.  * The information below is used for communication between processes
  117.  * during "send" commands.  Each process keeps a private window, never
  118.  * even mapped, with one property, "Comm".  When a command is sent to
  119.  * an interpreter, the command is appended to the comm property of the
  120.  * communication window associated with the interp's process.  Similarly,
  121.  * when a result is returned from a sent command, it is also appended
  122.  * to the comm property.
  123.  *
  124.  * Each command and each result takes the form of ASCII text.  For a
  125.  * command, the text consists of a zero character followed by several
  126.  * null-terminated ASCII strings.  The first string consists of the
  127.  * single letter "c".  Subsequent strings have the form "option value"
  128.  * where the following options are supported:
  129.  *
  130.  * -r commWindow serial
  131.  *
  132.  *    This option means that a response should be sent to the window
  133.  *    whose X identifier is "commWindow" (in hex), and the response should
  134.  *    be identified with the serial number given by "serial" (in decimal).
  135.  *    If this option isn't specified then the send is asynchronous and
  136.  *    no response is sent.
  137.  *
  138.  * -n name
  139.  *    "Name" gives the name of the application for which the command is
  140.  *    intended.  This option must be present.
  141.  *
  142.  * -s script
  143.  *
  144.  *    "Script" is the script to be executed.  This option must be present.
  145.  *
  146.  * The options may appear in any order.  The -n and -s options must be
  147.  * present, but -r may be omitted for asynchronous RPCs.  For compatibility
  148.  * with future releases that may add new features, there may be additional
  149.  * options present;  as long as they start with a "-" character, they will
  150.  * be ignored.
  151.  *
  152.  * A result also consists of a zero character followed by several null-
  153.  * terminated ASCII strings.  The first string consists of the single
  154.  * letter "r".  Subsequent strings have the form "option value" where
  155.  * the following options are supported:
  156.  *
  157.  * -s serial
  158.  *
  159.  *    Identifies the command for which this is the result.  It is the
  160.  *    same as the "serial" field from the -s option in the command.  This
  161.  *    option must be present.
  162.  *
  163.  * -c code
  164.  *
  165.  *    "Code" is the completion code for the script, in decimal.  If the
  166.  *    code is omitted it defaults to TCL_OK.
  167.  *
  168.  * -r result
  169.  *
  170.  *    "Result" is the result string for the script, which may be either
  171.  *    a result or an error message.  If this field is omitted then it
  172.  *    defaults to an empty string.
  173.  *
  174.  * -i errorInfo
  175.  *
  176.  *    "ErrorInfo" gives a string with which to initialize the errorInfo
  177.  *    variable.  This option may be omitted;  it is ignored unless the
  178.  *    completion code is TCL_ERROR.
  179.  *
  180.  * -e errorCode
  181.  *
  182.  *    "ErrorCode" gives a string with with to initialize the errorCode
  183.  *    variable.  This option may be omitted;  it is ignored  unless the
  184.  *    completion code is TCL_ERROR.
  185.  *
  186.  * Options may appear in any order, and only the -s option must be
  187.  * present.  As with commands, there may be additional options besides
  188.  * these;  unknown options are ignored.
  189.  */
  190.  
  191. /*
  192.  * The following variable is the serial number that was used in the
  193.  * last "send" command.  It is exported only for testing purposes.
  194.  */
  195.  
  196. int tkSendSerial = 0;
  197.  
  198. /*
  199.  * Maximum size property that can be read at one time by
  200.  * this module:
  201.  */
  202.  
  203. #define MAX_PROP_WORDS 100000
  204.  
  205. /*
  206.  * The following variable can be set while debugging to do things like
  207.  * skip locking the server.
  208.  */
  209.  
  210. static int sendDebug = 0;
  211.  
  212. /*
  213.  * Forward declarations for procedures defined later in this file:
  214.  */
  215.  
  216. static int        AppendErrorProc _ANSI_ARGS_((ClientData clientData,
  217.                 XErrorEvent *errorPtr));
  218. static void        AppendPropCarefully _ANSI_ARGS_((Display *display,
  219.                 Window window, Atom property, char *value,
  220.                 int length, PendingCommand *pendingPtr));
  221. static void        DeleteProc _ANSI_ARGS_((ClientData clientData));
  222. static void        RegAddName _ANSI_ARGS_((NameRegistry *regPtr,
  223.                 char *name, Window commWindow));
  224. static void        RegClose _ANSI_ARGS_((NameRegistry *regPtr));
  225. static void        RegDeleteName _ANSI_ARGS_((NameRegistry *regPtr,
  226.                 char *name));
  227. static Window        RegFindName _ANSI_ARGS_((NameRegistry *regPtr,
  228.                 char *name));
  229. static NameRegistry *    RegOpen _ANSI_ARGS_((Tcl_Interp *interp,
  230.                 TkDisplay *dispPtr, int lock));
  231. static void        SendEventProc _ANSI_ARGS_((ClientData clientData,
  232.                 XEvent *eventPtr));
  233. static int        SendInit _ANSI_ARGS_((Tcl_Interp *interp,
  234.                 TkDisplay *dispPtr));
  235. static Tk_RestrictAction SendRestrictProc _ANSI_ARGS_((ClientData clientData,
  236.                 XEvent *eventPtr));
  237. static int        ServerSecure _ANSI_ARGS_((TkDisplay *dispPtr));
  238. static void        TimeoutProc _ANSI_ARGS_((ClientData clientData));
  239. static void        UpdateCommWindow _ANSI_ARGS_((TkDisplay *dispPtr));
  240. static int        ValidateName _ANSI_ARGS_((TkDisplay *dispPtr,
  241.                 char *name, Window commWindow, int oldOK));
  242.  
  243. /*
  244.  *----------------------------------------------------------------------
  245.  *
  246.  * RegOpen --
  247.  *
  248.  *    This procedure loads the name registry for a display into
  249.  *    memory so that it can be manipulated.
  250.  *
  251.  * Results:
  252.  *    The return value is a pointer to the loaded registry.
  253.  *
  254.  * Side effects:
  255.  *    If "lock" is set then the server will be locked.  It is the
  256.  *    caller's responsibility to call RegClose when finished with
  257.  *    the registry, so that we can write back the registry if
  258.  *    neeeded, unlock the server if needed, and free memory.
  259.  *
  260.  *----------------------------------------------------------------------
  261.  */
  262.  
  263. static NameRegistry *
  264. RegOpen(interp, dispPtr, lock)
  265.     Tcl_Interp *interp;        /* Interpreter to use for error reporting
  266.                  * (errors cause a panic so in fact no
  267.                  * error is ever returned, but the interpreter
  268.                  * is needed anyway). */
  269.     TkDisplay *dispPtr;        /* Display whose name registry is to be
  270.                  * opened. */
  271.     int lock;            /* Non-zero means lock the window server
  272.                  * when opening the registry, so no-one
  273.                  * else can use the registry until we
  274.                  * close it. */
  275. {
  276.     NameRegistry *regPtr;
  277.     int result, actualFormat;
  278.     unsigned long bytesAfter;
  279.     Atom actualType;
  280.  
  281.     if (dispPtr->commTkwin == NULL) {
  282.     SendInit(interp, dispPtr);
  283.     }
  284.  
  285.     regPtr = (NameRegistry *) ckalloc(sizeof(NameRegistry));
  286.     regPtr->dispPtr = dispPtr;
  287.     regPtr->locked = 0;
  288.     regPtr->modified = 0;
  289.     regPtr->allocedByX = 1;
  290.  
  291.     if (lock && !sendDebug) {
  292.     XGrabServer(dispPtr->display);
  293.     regPtr->locked = 1;
  294.     }
  295.  
  296.     /*
  297.      * Read the registry property.
  298.      */
  299.  
  300.     result = XGetWindowProperty(dispPtr->display,
  301.         RootWindow(dispPtr->display, 0),
  302.         dispPtr->registryProperty, 0, MAX_PROP_WORDS,
  303.         False, XA_STRING, &actualType, &actualFormat,
  304.         ®Ptr->propLength, &bytesAfter,
  305.         (unsigned char **) ®Ptr->property);
  306.  
  307.     if (actualType == None) {
  308.     regPtr->propLength = 0;
  309.     regPtr->property = NULL;
  310.     } else if ((result != Success) || (actualFormat != 8)
  311.         || (actualType != XA_STRING)) {
  312.     /*
  313.      * The property is improperly formed;  delete it.
  314.      */
  315.  
  316.     if (regPtr->property != NULL) {
  317.         XFree(regPtr->property);
  318.         regPtr->propLength = 0;
  319.         regPtr->property = NULL;
  320.     }
  321.     XDeleteProperty(dispPtr->display,
  322.         RootWindow(dispPtr->display, 0),
  323.         dispPtr->registryProperty);
  324.     }
  325.  
  326.     /*
  327.      * Xlib placed an extra null byte after the end of the property, just
  328.      * to make sure that it is always NULL-terminated.  Be sure to include
  329.      * this byte in our count if it's needed to ensure null termination
  330.      * (note: as of 8/95 I'm no longer sure why this code is needed;  seems
  331.      * like it shouldn't be).
  332.      */
  333.  
  334.     if ((regPtr->propLength > 0)
  335.         && (regPtr->property[regPtr->propLength-1] != 0)) {
  336.     regPtr->propLength++;
  337.     }
  338.     return regPtr;
  339. }
  340.  
  341. /*
  342.  *----------------------------------------------------------------------
  343.  *
  344.  * RegFindName --
  345.  *
  346.  *    Given an open name registry, this procedure finds an entry
  347.  *    with a given name, if there is one, and returns information
  348.  *    about that entry.
  349.  *
  350.  * Results:
  351.  *    The return value is the X identifier for the comm window for
  352.  *    the application named "name", or None if there is no such
  353.  *    entry in the registry.
  354.  *
  355.  * Side effects:
  356.  *    None.
  357.  *
  358.  *----------------------------------------------------------------------
  359.  */
  360.  
  361. static Window
  362. RegFindName(regPtr, name)
  363.     NameRegistry *regPtr;    /* Pointer to a registry opened with a
  364.                  * previous call to RegOpen. */
  365.     char *name;            /* Name of an application. */
  366. {
  367.     char *p, *entry;
  368.     Window commWindow;
  369.  
  370.     commWindow = None;
  371.     for (p = regPtr->property; (p-regPtr->property) < regPtr->propLength; ) {
  372.     entry = p;
  373.     while ((*p != 0) && (!isspace(UCHAR(*p)))) {
  374.         p++;
  375.     }
  376.     if ((*p != 0) && (strcmp(name, p+1) == 0)) {
  377.         if (sscanf(entry, "%x", (unsigned int *) &commWindow) == 1) {
  378.         return commWindow;
  379.         }
  380.     }
  381.     while (*p != 0) {
  382.         p++;
  383.     }
  384.     p++;
  385.     }
  386.     return None;
  387. }
  388.  
  389. /*
  390.  *----------------------------------------------------------------------
  391.  *
  392.  * RegDeleteName --
  393.  *
  394.  *    This procedure deletes the entry for a given name from
  395.  *    an open registry.
  396.  *
  397.  * Results:
  398.  *    None.
  399.  *
  400.  * Side effects:
  401.  *    If there used to be an entry named "name" in the registry,
  402.  *    then it is deleted and the registry is marked as modified
  403.  *    so it will be written back when closed.
  404.  *
  405.  *----------------------------------------------------------------------
  406.  */
  407.  
  408. static void
  409. RegDeleteName(regPtr, name)
  410.     NameRegistry *regPtr;    /* Pointer to a registry opened with a
  411.                  * previous call to RegOpen. */
  412.     char *name;            /* Name of an application. */
  413. {
  414.     char *p, *entry, *entryName;
  415.     int count;
  416.  
  417.     for (p = regPtr->property; (p-regPtr->property) < regPtr->propLength; ) {
  418.     entry = p;
  419.     while ((*p != 0) && (!isspace(UCHAR(*p)))) {
  420.         p++;
  421.     }
  422.     if (*p != 0) {
  423.         p++;
  424.     }
  425.     entryName = p;
  426.     while (*p != 0) {
  427.         p++;
  428.     }
  429.     p++;
  430.     if ((strcmp(name, entryName) == 0)) {
  431.         /*
  432.          * Found the matching entry.  Copy everything after it
  433.          * down on top of it.
  434.          */
  435.  
  436.         count = regPtr->propLength - (p - regPtr->property);
  437.         if (count > 0)  {
  438.         memmove((VOID *) entry, (VOID *) p, (size_t) count);
  439.         }
  440.         regPtr->propLength -=  p - entry;
  441.         regPtr->modified = 1;
  442.         return;
  443.     }
  444.     }
  445. }
  446.  
  447. /*
  448.  *----------------------------------------------------------------------
  449.  *
  450.  * RegAddName --
  451.  *
  452.  *    Add a new entry to an open registry.
  453.  *
  454.  * Results:
  455.  *    None.
  456.  *
  457.  * Side effects:
  458.  *    The open registry is expanded;  it is marked as modified so that
  459.  *    it will be written back when closed.
  460.  *
  461.  *----------------------------------------------------------------------
  462.  */
  463.  
  464. static void
  465. RegAddName(regPtr, name, commWindow)
  466.     NameRegistry *regPtr;    /* Pointer to a registry opened with a
  467.                  * previous call to RegOpen. */
  468.     char *name;            /* Name of an application.  The caller
  469.                  * must ensure that this name isn't
  470.                  * already registered. */
  471.     Window commWindow;        /* X identifier for comm. window of
  472.                  * application.  */
  473. {
  474.     char id[30];
  475.     char *newProp;
  476.     int idLength, newBytes;
  477.  
  478.     sprintf(id, "%x ", (unsigned int) commWindow);
  479.     idLength = strlen(id);
  480.     newBytes = idLength + strlen(name) + 1;
  481.     newProp = (char *) ckalloc((unsigned) (regPtr->propLength + newBytes));
  482.     strcpy(newProp, id);
  483.     strcpy(newProp+idLength, name);
  484.     if (regPtr->property != NULL) {
  485.     memcpy((VOID *) (newProp + newBytes), (VOID *) regPtr->property,
  486.         regPtr->propLength);
  487.     if (regPtr->allocedByX) {
  488.         XFree(regPtr->property);
  489.     } else {
  490.         ckfree(regPtr->property);
  491.     }
  492.     }
  493.     regPtr->modified = 1;
  494.     regPtr->propLength += newBytes;
  495.     regPtr->property = newProp;
  496.     regPtr->allocedByX = 0;
  497. }
  498.  
  499. /*
  500.  *----------------------------------------------------------------------
  501.  *
  502.  * RegClose --
  503.  *
  504.  *    This procedure is called to end a series of operations on
  505.  *    a name registry.
  506.  *
  507.  * Results:
  508.  *    None.
  509.  *
  510.  * Side effects:
  511.  *    The registry is written back if it has been modified, and the
  512.  *    X server is unlocked if it was locked.  Memory for the
  513.  *    registry is freed, so the caller should never use regPtr
  514.  *    again.
  515.  *
  516.  *----------------------------------------------------------------------
  517.  */
  518.  
  519. static void
  520. RegClose(regPtr)
  521.     NameRegistry *regPtr;    /* Pointer to a registry opened with a
  522.                  * previous call to RegOpen. */
  523. {
  524.     if (regPtr->modified) {
  525.     if (!regPtr->locked && !sendDebug) {
  526.         panic("The name registry was modified without being locked!");
  527.     }
  528.     XChangeProperty(regPtr->dispPtr->display,
  529.         RootWindow(regPtr->dispPtr->display, 0),
  530.         regPtr->dispPtr->registryProperty, XA_STRING, 8,
  531.         PropModeReplace, (unsigned char *) regPtr->property,
  532.         (int) regPtr->propLength);
  533.     }
  534.  
  535.     if (regPtr->locked) {
  536.     XUngrabServer(regPtr->dispPtr->display);
  537.     }
  538.     XFlush(regPtr->dispPtr->display);
  539.  
  540.     if (regPtr->property != NULL) {
  541.     if (regPtr->allocedByX) {
  542.         XFree(regPtr->property);
  543.     } else {
  544.         ckfree(regPtr->property);
  545.     }
  546.     }
  547.     ckfree((char *) regPtr);
  548. }
  549.  
  550. /*
  551.  *----------------------------------------------------------------------
  552.  *
  553.  * ValidateName --
  554.  *
  555.  *    This procedure checks to see if an entry in the registry
  556.  *    is still valid.
  557.  *
  558.  * Results:
  559.  *    The return value is 1 if the given commWindow exists and its
  560.  *    name is "name".  Otherwise 0 is returned.
  561.  *
  562.  * Side effects:
  563.  *    None.
  564.  *
  565.  *----------------------------------------------------------------------
  566.  */
  567.  
  568. static int
  569. ValidateName(dispPtr, name, commWindow, oldOK)
  570.     TkDisplay *dispPtr;        /* Display for which to perform the
  571.                  * validation. */
  572.     char *name;            /* The name of an application. */
  573.     Window commWindow;        /* X identifier for the application's
  574.                  * comm. window. */
  575.     int oldOK;            /* Non-zero means that we should consider
  576.                  * an application to be valid even if it
  577.                  * looks like an old-style (pre-4.0) one;
  578.                  * 0 means consider these invalid. */
  579. {
  580.     int result, actualFormat, argc, i;
  581.     unsigned long length, bytesAfter;
  582.     Atom actualType;
  583.     char *property;
  584.     Tk_ErrorHandler handler;
  585.     char **argv;
  586.  
  587.     property = NULL;
  588.  
  589.     /*
  590.      * Ignore X errors when reading the property (e.g., the window
  591.      * might not exist).  If an error occurs, result will be some
  592.      * value other than Success.
  593.      */
  594.  
  595.     handler = Tk_CreateErrorHandler(dispPtr->display, -1, -1, -1,
  596.         (Tk_ErrorProc *) NULL, (ClientData) NULL);
  597.     result = XGetWindowProperty(dispPtr->display, commWindow,
  598.         dispPtr->appNameProperty, 0, MAX_PROP_WORDS,
  599.         False, XA_STRING, &actualType, &actualFormat,
  600.         &length, &bytesAfter, (unsigned char **) &property);
  601.  
  602.     if ((result == Success) && (actualType == None)) {
  603.     XWindowAttributes atts;
  604.  
  605.     /*
  606.      * The comm. window exists but the property we're looking for
  607.      * doesn't exist.  This probably means that the application
  608.      * comes from an older version of Tk (< 4.0) that didn't set the
  609.      * property;  if this is the case, then assume for compatibility's
  610.      * sake that everything's OK.  However, it's also possible that
  611.      * some random application has re-used the window id for something
  612.      * totally unrelated.  Check a few characteristics of the window,
  613.      * such as its dimensions and mapped state, to be sure that it
  614.      * still "smells" like a commWindow.
  615.      */
  616.  
  617.     if (!oldOK
  618.         || !XGetWindowAttributes(dispPtr->display, commWindow, &atts)
  619.         || (atts.width != 1) || (atts.height != 1)
  620.         || (atts.map_state != IsUnmapped)) {
  621.         result = 0;
  622.     } else {
  623.         result = 1;
  624.     }
  625.     } else if ((result == Success) && (actualFormat == 8)
  626.        && (actualType == XA_STRING)) {
  627.     result = 0;
  628.     if (Tcl_SplitList((Tcl_Interp *) NULL, property, &argc, &argv)
  629.         == TCL_OK) {
  630.         for (i = 0; i < argc; i++) {
  631.         if (strcmp(argv[i], name) == 0) {
  632.             result = 1;
  633.             break;
  634.         }
  635.         }
  636.         ckfree((char *) argv);
  637.     }
  638.     } else {
  639.        result = 0;
  640.     }
  641.     Tk_DeleteErrorHandler(handler);
  642.     if (property != NULL) {
  643.     XFree(property);
  644.     }
  645.     return result;
  646. }
  647.  
  648. /*
  649.  *----------------------------------------------------------------------
  650.  *
  651.  * ServerSecure --
  652.  *
  653.  *    Check whether a server is secure enough for us to trust
  654.  *    Tcl scripts arriving via that server.
  655.  *
  656.  * Results:
  657.  *    The return value is 1 if the server is secure, which means
  658.  *    that host-style authentication is turned on but there are
  659.  *    no hosts in the enabled list.  This means that some other
  660.  *    form of authorization (presumably more secure, such as xauth)
  661.  *    is in use.
  662.  *
  663.  * Side effects:
  664.  *    None.
  665.  *
  666.  *----------------------------------------------------------------------
  667.  */
  668.  
  669. static int
  670. ServerSecure(dispPtr)
  671.     TkDisplay *dispPtr;        /* Display to check. */
  672. {
  673. #ifdef TK_NO_SECURITY
  674.     return 1;
  675. #else
  676.     XHostAddress *addrPtr;
  677.     int numHosts, secure;
  678.     Bool enabled;
  679.  
  680.     secure = 0;
  681.     addrPtr = XListHosts(dispPtr->display, &numHosts, &enabled);
  682.     if (enabled && (numHosts == 0)) {
  683.     secure = 1;
  684.     }
  685.     if (addrPtr != NULL) {
  686.     XFree((char *) addrPtr);
  687.     }
  688.     return secure;
  689. #endif /* TK_NO_SECURITY */
  690. }
  691.  
  692. /*
  693.  *--------------------------------------------------------------
  694.  *
  695.  * Tk_SetAppName --
  696.  *
  697.  *    This procedure is called to associate an ASCII name with a Tk
  698.  *    application.  If the application has already been named, the
  699.  *    name replaces the old one.
  700.  *
  701.  * Results:
  702.  *    The return value is the name actually given to the application.
  703.  *    This will normally be the same as name, but if name was already
  704.  *    in use for an application then a name of the form "name #2" will
  705.  *    be chosen,  with a high enough number to make the name unique.
  706.  *
  707.  * Side effects:
  708.  *    Registration info is saved, thereby allowing the "send" command
  709.  *    to be used later to invoke commands in the application.  In
  710.  *    addition, the "send" command is created in the application's
  711.  *    interpreter.  The registration will be removed automatically
  712.  *    if the interpreter is deleted or the "send" command is removed.
  713.  *
  714.  *--------------------------------------------------------------
  715.  */
  716.  
  717. char *
  718. Tk_SetAppName(tkwin, name)
  719.     Tk_Window tkwin;        /* Token for any window in the application
  720.                  * to be named:  it is just used to identify
  721.                  * the application and the display.  */
  722.     char *name;            /* The name that will be used to
  723.                  * refer to the interpreter in later
  724.                  * "send" commands.  Must be globally
  725.                  * unique. */
  726. {
  727.     RegisteredInterp *riPtr, *riPtr2;
  728.     Window w;
  729.     TkWindow *winPtr = (TkWindow *) tkwin;
  730.     TkDisplay *dispPtr;
  731.     NameRegistry *regPtr;
  732.     Tcl_Interp *interp;
  733.     char *actualName;
  734.     Tcl_DString dString;
  735.     int offset, i;
  736.  
  737. #ifdef __WIN32__
  738.     return name;
  739. #endif /* __WIN32__ */
  740.  
  741.     dispPtr = winPtr->dispPtr;
  742.     interp = winPtr->mainPtr->interp;
  743.     if (dispPtr->commTkwin == NULL) {
  744.     SendInit(interp, winPtr->dispPtr);
  745.     }
  746.  
  747.     /*
  748.      * See if the application is already registered;  if so, remove its
  749.      * current name from the registry.
  750.      */
  751.  
  752.     regPtr = RegOpen(interp, winPtr->dispPtr, 1);
  753.     for (riPtr = registry; ; riPtr = riPtr->nextPtr) {
  754.     if (riPtr == NULL) {
  755.         /*
  756.          * This interpreter isn't currently registered;  create
  757.          * the data structure that will be used to register it locally,
  758.          * plus add the "send" command to the interpreter.
  759.          */
  760.  
  761.         riPtr = (RegisteredInterp *) ckalloc(sizeof(RegisteredInterp));
  762.         riPtr->interp = interp;
  763.         riPtr->dispPtr = winPtr->dispPtr;
  764.         riPtr->nextPtr = registry;
  765.         registry = riPtr;
  766.         Tcl_CreateCommand(interp, "send", Tk_SendCmd, (ClientData) riPtr,
  767.             DeleteProc);
  768.         break;
  769.     }
  770.     if (riPtr->interp == interp) {
  771.         /*
  772.          * The interpreter is currently registered;  remove it from
  773.          * the name registry.
  774.          */
  775.  
  776.         RegDeleteName(regPtr, riPtr->name);
  777.         ckfree(riPtr->name);
  778.         break;
  779.     }
  780.     }
  781.  
  782.     /*
  783.      * Pick a name to use for the application.  Use "name" if it's not
  784.      * already in use.  Otherwise add a suffix such as " #2", trying
  785.      * larger and larger numbers until we eventually find one that is
  786.      * unique.
  787.      */
  788.  
  789.     actualName = name;
  790.     offset = 0;                /* Needed only to avoid "used before
  791.                      * set" compiler warnings. */
  792.     for (i = 1; ; i++) {
  793.     if (i > 1) {
  794.         if (i == 2) {
  795.         Tcl_DStringInit(&dString);
  796.         Tcl_DStringAppend(&dString, name, -1);
  797.         Tcl_DStringAppend(&dString, " #", 2);
  798.         offset = Tcl_DStringLength(&dString);
  799.         Tcl_DStringSetLength(&dString, offset+10);
  800.         actualName = Tcl_DStringValue(&dString);
  801.         }
  802.         sprintf(actualName + offset, "%d", i);
  803.     }
  804.     w = RegFindName(regPtr, actualName);
  805.     if (w == None) {
  806.         break;
  807.     }
  808.     
  809.     /*
  810.      * The name appears to be in use already, but double-check to
  811.      * be sure (perhaps the application died without removing its
  812.      * name from the registry?).
  813.      */
  814.  
  815.     if (w == Tk_WindowId(dispPtr->commTkwin)) {
  816.         for (riPtr2 = registry; riPtr2 != NULL; riPtr2 = riPtr2->nextPtr) {
  817.         if ((riPtr2->interp != interp) &&
  818.             (strcmp(riPtr2->name, actualName) == 0)) {
  819.             goto nextSuffix;
  820.         }
  821.         }
  822.         RegDeleteName(regPtr, actualName);
  823.         break;
  824.     } else if (!ValidateName(winPtr->dispPtr, actualName, w, 1)) {
  825.         RegDeleteName(regPtr, actualName);
  826.         break;
  827.     }
  828.     nextSuffix:
  829.     continue;
  830.     }
  831.  
  832.     /*
  833.      * We've now got a name to use.  Store it in the name registry and
  834.      * in the local entry for this application, plus put it in a property
  835.      * on the commWindow.
  836.      */
  837.  
  838.     RegAddName(regPtr, actualName, Tk_WindowId(dispPtr->commTkwin));
  839.     RegClose(regPtr);
  840.     riPtr->name = (char *) ckalloc((unsigned) (strlen(actualName) + 1));
  841.     strcpy(riPtr->name, actualName);
  842.     if (actualName != name) {
  843.     Tcl_DStringFree(&dString);
  844.     }
  845.     UpdateCommWindow(dispPtr);
  846.  
  847.     return riPtr->name;
  848. }
  849.  
  850. /*
  851.  *--------------------------------------------------------------
  852.  *
  853.  * Tk_SendCmd --
  854.  *
  855.  *    This procedure is invoked to process the "send" Tcl command.
  856.  *    See the user documentation for details on what it does.
  857.  *
  858.  * Results:
  859.  *    A standard Tcl result.
  860.  *
  861.  * Side effects:
  862.  *    See the user documentation.
  863.  *
  864.  *--------------------------------------------------------------
  865.  */
  866.  
  867. int
  868. Tk_SendCmd(clientData, interp, argc, argv)
  869.     ClientData clientData;        /* Information about sender (only
  870.                      * dispPtr field is used). */
  871.     Tcl_Interp *interp;            /* Current interpreter. */
  872.     int argc;                /* Number of arguments. */
  873.     char **argv;            /* Argument strings. */
  874. {
  875.     TkWindow *winPtr;
  876.     Window commWindow;
  877.     PendingCommand pending;
  878.     register RegisteredInterp *riPtr;
  879.     char *destName, buffer[30];
  880.     int result, c, async, i, firstArg;
  881.     size_t length;
  882.     Tk_RestrictProc *prevRestrictProc;
  883.     ClientData prevArg;
  884.     TkDisplay *dispPtr;
  885.     NameRegistry *regPtr;
  886.     Tcl_DString request;
  887.     Tcl_Interp *localInterp;        /* Used when the interpreter to
  888.                                          * send the command to is within
  889.                                          * the same process. */
  890.  
  891.     /*
  892.      * Process options, if any.
  893.      */
  894.  
  895.     async = 0;
  896.     winPtr = (TkWindow *) Tk_MainWindow(interp);
  897.     if (winPtr == NULL) {
  898.     return TCL_ERROR;
  899.     }
  900.     for (i = 1; i < (argc-1); ) {
  901.     if (argv[i][0] != '-') {
  902.         break;
  903.     }
  904.     c = argv[i][1];
  905.     length = strlen(argv[i]);
  906.     if ((c == 'a') && (strncmp(argv[i], "-async", length) == 0)) {
  907.         async = 1;
  908.         i++;
  909.     } else if ((c == 'd') && (strncmp(argv[i], "-displayof",
  910.         length) == 0)) {
  911.         winPtr = (TkWindow *) Tk_NameToWindow(interp, argv[i+1],
  912.             (Tk_Window) winPtr);
  913.         if (winPtr == NULL) {
  914.         return TCL_ERROR;
  915.         }
  916.         i += 2;
  917.     } else if (strcmp(argv[i], "--") == 0) {
  918.         i++;
  919.         break;
  920.     } else {
  921.         Tcl_AppendResult(interp, "bad option \"", argv[i],
  922. #ifdef STk_CODE
  923.             "\": must be :async, :displayof, or :-", (char *) NULL);
  924. #else
  925.             "\": must be -async, -displayof, or --", (char *) NULL);
  926. #endif
  927.         return TCL_ERROR;
  928.     }
  929.     }
  930.  
  931.     if (argc < (i+2)) {
  932.     Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
  933.         " ?options? interpName arg ?arg ...?\"", (char *) NULL);
  934.     return TCL_ERROR;
  935.     }
  936.     destName = argv[i];
  937.     firstArg = i+1;
  938.  
  939.     dispPtr = winPtr->dispPtr;
  940.     if (dispPtr->commTkwin == NULL) {
  941.     SendInit(interp, winPtr->dispPtr);
  942.     }
  943.  
  944.     /*
  945.      * See if the target interpreter is local.  If so, execute
  946.      * the command directly without going through the X server.
  947.      * The only tricky thing is passing the result from the target
  948.      * interpreter to the invoking interpreter.  Watch out:  they
  949.      * could be the same!
  950.      */
  951.  
  952.     for (riPtr = registry; riPtr != NULL; riPtr = riPtr->nextPtr) {
  953.     if ((riPtr->dispPtr != dispPtr)
  954.         || (strcmp(riPtr->name, destName) != 0)) {
  955.         continue;
  956.     }
  957.     Tcl_Preserve((ClientData) riPtr);
  958.         localInterp = riPtr->interp;
  959.         Tcl_Preserve((ClientData) localInterp);
  960.     if (firstArg == (argc-1)) {
  961.         result = Tcl_GlobalEval(localInterp, argv[firstArg]);
  962.     } else {
  963.         Tcl_DStringInit(&request);
  964.         Tcl_DStringAppend(&request, argv[firstArg], -1);
  965.         for (i = firstArg+1; i < argc; i++) {
  966.         Tcl_DStringAppend(&request, " ", 1);
  967.         Tcl_DStringAppend(&request, argv[i], -1);
  968.         }
  969.         result = Tcl_GlobalEval(localInterp, Tcl_DStringValue(&request));
  970.         Tcl_DStringFree(&request);
  971.     }
  972.     if (interp != localInterp) {
  973.         if (result == TCL_ERROR) {
  974.  
  975.         /*
  976.          * An error occurred, so transfer error information from the
  977.          * destination interpreter back to our interpreter.  Must clear
  978.          * interp's result before calling Tcl_AddErrorInfo, since
  979.          * Tcl_AddErrorInfo will store the interp's result in errorInfo
  980.          * before appending riPtr's $errorInfo;  we've already got
  981.          * everything we need in riPtr's $errorInfo.
  982.          */
  983.  
  984.         Tcl_ResetResult(interp);
  985. #ifdef STk_CODE
  986.         Tcl_AddErrorInfo(interp, Tcl_GetVar2(localInterp,
  987.             "*error-info*", (char *) NULL, TCL_GLOBAL_ONLY));
  988.         Tcl_SetVar(interp, "*error-code*",
  989.                Tcl_GetVar(localInterp, "*error-code*",TCL_GLOBAL_ONLY), 
  990.                STk_STRINGIFY | TCL_GLOBAL_ONLY);
  991. #else
  992.         Tcl_AddErrorInfo(interp, Tcl_GetVar2(localInterp,
  993.             "errorInfo", (char *) NULL, TCL_GLOBAL_ONLY));
  994.         Tcl_SetVar2(interp, "errorCode", (char *) NULL,
  995.             Tcl_GetVar2(localInterp, "errorCode", (char *) NULL,
  996.             TCL_GLOBAL_ONLY), TCL_GLOBAL_ONLY);
  997. #endif
  998.         }
  999.             if (localInterp->freeProc != TCL_STATIC) {
  1000.                 interp->result = localInterp->result;
  1001.                 interp->freeProc = localInterp->freeProc;
  1002.                 localInterp->freeProc = TCL_STATIC;
  1003.             } else {
  1004.                 Tcl_SetResult(interp, localInterp->result, TCL_VOLATILE);
  1005.             }
  1006.             Tcl_ResetResult(localInterp);
  1007.     }
  1008.     Tcl_Release((ClientData) riPtr);
  1009.         Tcl_Release((ClientData) localInterp);
  1010.     return result;
  1011.     }
  1012.  
  1013.     /*
  1014.      * Bind the interpreter name to a communication window.
  1015.      */
  1016.  
  1017.     regPtr = RegOpen(interp, winPtr->dispPtr, 0);
  1018.     commWindow = RegFindName(regPtr, destName);
  1019.     RegClose(regPtr);
  1020.     if (commWindow == None) {
  1021.     Tcl_AppendResult(interp, "no application named \"",
  1022.         destName, "\"", (char *) NULL);
  1023.     return TCL_ERROR;
  1024.     }
  1025.  
  1026.     /*
  1027.      * Send the command to the target interpreter by appending it to the
  1028.      * comm window in the communication window.
  1029.      */
  1030.  
  1031.     tkSendSerial++;
  1032.     Tcl_DStringInit(&request);
  1033.     Tcl_DStringAppend(&request, "\0c\0-n ", 6);
  1034.     Tcl_DStringAppend(&request, destName, -1);
  1035.     if (!async) {
  1036.     sprintf(buffer, "%x %d",
  1037.         (unsigned int) Tk_WindowId(dispPtr->commTkwin),
  1038.         tkSendSerial);
  1039.     Tcl_DStringAppend(&request, "\0-r ", 4);
  1040.     Tcl_DStringAppend(&request, buffer, -1);
  1041.     }
  1042.     Tcl_DStringAppend(&request, "\0-s ", 4);
  1043.     Tcl_DStringAppend(&request, argv[firstArg], -1);
  1044.     for (i = firstArg+1; i < argc; i++) {
  1045.     Tcl_DStringAppend(&request, " ", 1);
  1046.     Tcl_DStringAppend(&request, argv[i], -1);
  1047.     }
  1048.     (void) AppendPropCarefully(dispPtr->display, commWindow,
  1049.         dispPtr->commProperty, Tcl_DStringValue(&request),
  1050.         Tcl_DStringLength(&request) + 1,
  1051.         (async) ? (PendingCommand *) NULL : &pending);
  1052.     Tcl_DStringFree(&request);
  1053.     if (async) {
  1054.     /*
  1055.      * This is an asynchronous send:  return immediately without
  1056.      * waiting for a response.
  1057.      */
  1058.  
  1059.     return TCL_OK;
  1060.     }
  1061.  
  1062.     /*
  1063.      * Register the fact that we're waiting for a command to complete
  1064.      * (this is needed by SendEventProc and by AppendErrorProc to pass
  1065.      * back the command's results).  Set up a timeout handler so that
  1066.      * we can check during long sends to make sure that the destination
  1067.      * application is still alive.
  1068.      */
  1069.  
  1070.     pending.serial = tkSendSerial;
  1071.     pending.dispPtr = dispPtr;
  1072.     pending.target = destName;
  1073.     pending.commWindow = commWindow;
  1074.     pending.interp = interp;
  1075.     pending.result = NULL;
  1076.     pending.errorInfo = NULL;
  1077.     pending.errorCode = NULL;
  1078.     pending.gotResponse = 0;
  1079.     pending.nextPtr = pendingCommands;
  1080.     pendingCommands = &pending;
  1081.  
  1082.     /*
  1083.      * Enter a loop processing X events until the result comes
  1084.      * in or the target is declared to be dead.  While waiting
  1085.      * for a result, look only at send-related events so that
  1086.      * the send is synchronous with respect to other events in
  1087.      * the application.
  1088.      */
  1089.  
  1090.     prevRestrictProc = Tk_RestrictEvents(SendRestrictProc,
  1091.         (ClientData) dispPtr->commTkwin, &prevArg);
  1092.     Tcl_CreateModalTimeout(1000, TimeoutProc, (ClientData) &pending);
  1093.     while (!pending.gotResponse) {
  1094.     Tcl_DoOneEvent(TCL_WINDOW_EVENTS);
  1095.     }
  1096.     Tcl_DeleteModalTimeout(TimeoutProc, (ClientData) &pending);
  1097.     (void) Tk_RestrictEvents(prevRestrictProc, prevArg, &prevArg);
  1098.  
  1099.     /*
  1100.      * Unregister the information about the pending command
  1101.      * and return the result.
  1102.      */
  1103.  
  1104.     if (pendingCommands == &pending) {
  1105.     pendingCommands = pending.nextPtr;
  1106.     } else {
  1107.     PendingCommand *pcPtr;
  1108.  
  1109.     for (pcPtr = pendingCommands; pcPtr != NULL;
  1110.         pcPtr = pcPtr->nextPtr) {
  1111.         if (pcPtr->nextPtr == &pending) {
  1112.         pcPtr->nextPtr = pending.nextPtr;
  1113.         break;
  1114.         }
  1115.     }
  1116.     }
  1117.     if (pending.errorInfo != NULL) {
  1118.     /*
  1119.      * Special trick: must clear the interp's result before calling
  1120.      * Tcl_AddErrorInfo, since Tcl_AddErrorInfo will store the interp's
  1121.      * result in errorInfo before appending pending.errorInfo;  we've
  1122.      * already got everything we need in pending.errorInfo.
  1123.      */
  1124.  
  1125.     Tcl_ResetResult(interp);
  1126.     Tcl_AddErrorInfo(interp, pending.errorInfo);
  1127.     ckfree(pending.errorInfo);
  1128.     }
  1129.     if (pending.errorCode != NULL) {
  1130. #ifdef STk_CODE
  1131.         Tcl_SetVar(interp, "*error-code*", pending.errorCode,
  1132.                   STk_STRINGIFY |
  1133.  
  1134. #else
  1135.     Tcl_SetVar2(interp, "errorCode", (char *) NULL, pending.errorCode,
  1136. #endif
  1137.         TCL_GLOBAL_ONLY);
  1138.     ckfree(pending.errorCode);
  1139.     }
  1140.     Tcl_SetResult(interp, pending.result, TCL_DYNAMIC);
  1141.     return pending.code;
  1142. }
  1143.  
  1144. /*
  1145.  *----------------------------------------------------------------------
  1146.  *
  1147.  * TkGetInterpNames --
  1148.  *
  1149.  *    This procedure is invoked to fetch a list of all the
  1150.  *    interpreter names currently registered for the display
  1151.  *    of a particular window.
  1152.  *
  1153.  * Results:
  1154.  *    A standard Tcl return value.  Interp->result will be set
  1155.  *    to hold a list of all the interpreter names defined for
  1156.  *    tkwin's display.  If an error occurs, then TCL_ERROR
  1157.  *    is returned and interp->result will hold an error message.
  1158.  *
  1159.  * Side effects:
  1160.  *    None.
  1161.  *
  1162.  *----------------------------------------------------------------------
  1163.  */
  1164.  
  1165. int
  1166. TkGetInterpNames(interp, tkwin)
  1167.     Tcl_Interp *interp;        /* Interpreter for returning a result. */
  1168.     Tk_Window tkwin;        /* Window whose display is to be used
  1169.                  * for the lookup. */
  1170. {
  1171.     TkWindow *winPtr = (TkWindow *) tkwin;
  1172.     char *p, *entry, *entryName;
  1173.     NameRegistry *regPtr;
  1174.     Window commWindow;
  1175.     int count;
  1176.  
  1177.     /*
  1178.      * Read the registry property, then scan through all of its entries.
  1179.      * Validate each entry to be sure that its application still exists.
  1180.      */
  1181.  
  1182.     regPtr = RegOpen(interp, winPtr->dispPtr, 1);
  1183. #ifdef STk_CODE
  1184.     Tcl_AppendElement(interp, "(");
  1185. #endif
  1186.     for (p = regPtr->property; (p-regPtr->property) < regPtr->propLength; ) {
  1187.     entry = p;
  1188.     if (sscanf(p,  "%x",(unsigned int *) &commWindow) != 1) {
  1189.         commWindow =  None;
  1190.     }
  1191.     while ((*p != 0) && (!isspace(UCHAR(*p)))) {
  1192.         p++;
  1193.     }
  1194.     if (*p != 0) {
  1195.         p++;
  1196.     }
  1197.     entryName = p;
  1198.     while (*p != 0) {
  1199.         p++;
  1200.     }
  1201.     p++;
  1202.     if (ValidateName(winPtr->dispPtr, entryName, commWindow, 1)) {
  1203.         /*
  1204.          * The application still exists; add its name to the result.
  1205.          */
  1206.  
  1207. #ifdef STk_CODE
  1208.         Tcl_AppendElement(interp, (char*) STk_stringify(entryName, 0));
  1209. #else
  1210.         Tcl_AppendElement(interp, entryName);
  1211. #endif
  1212.     } else {
  1213.         /*
  1214.          * This name is bogus (perhaps the application died without
  1215.          * cleaning up its entry in the registry?).  Delete the name.
  1216.          */
  1217.  
  1218.         count = regPtr->propLength - (p - regPtr->property);
  1219.         if (count > 0)  {
  1220.         memmove((VOID *) entry, (VOID *) p, (size_t) count);
  1221.         }
  1222.         regPtr->propLength -= p - entry;
  1223.         regPtr->modified = 1;
  1224.         p = entry;
  1225.     }
  1226.     }
  1227. #ifdef STk_CODE
  1228.     Tcl_AppendElement(interp, ")");
  1229. #endif
  1230.     RegClose(regPtr);
  1231.     return TCL_OK;
  1232. }
  1233.  
  1234. /*
  1235.  *--------------------------------------------------------------
  1236.  *
  1237.  * SendInit --
  1238.  *
  1239.  *    This procedure is called to initialize the
  1240.  *    communication channels for sending commands and
  1241.  *    receiving results.
  1242.  *
  1243.  * Results:
  1244.  *    None.
  1245.  *
  1246.  * Side effects:
  1247.  *    Sets up various data structures and windows.
  1248.  *
  1249.  *--------------------------------------------------------------
  1250.  */
  1251.  
  1252. static int
  1253. SendInit(interp, dispPtr)
  1254.     Tcl_Interp *interp;        /* Interpreter to use for error reporting
  1255.                  * (no errors are ever returned, but the
  1256.                  * interpreter is needed anyway). */
  1257.     TkDisplay *dispPtr;        /* Display to initialize. */
  1258. {
  1259.     XSetWindowAttributes atts;
  1260.  
  1261.     /*
  1262.      * Create the window used for communication, and set up an
  1263.      * event handler for it.
  1264.      */
  1265.  
  1266.     dispPtr->commTkwin = Tk_CreateWindow(interp, (Tk_Window) NULL,
  1267.         "_comm", DisplayString(dispPtr->display));
  1268.     if (dispPtr->commTkwin == NULL) {
  1269.     panic("Tk_CreateWindow failed in SendInit!");
  1270.     }
  1271.     atts.override_redirect = True;
  1272.     Tk_ChangeWindowAttributes(dispPtr->commTkwin,
  1273.         CWOverrideRedirect, &atts);
  1274.     Tk_CreateEventHandler(dispPtr->commTkwin, PropertyChangeMask,
  1275.         SendEventProc, (ClientData) dispPtr);
  1276.     Tk_MakeWindowExist(dispPtr->commTkwin);
  1277.  
  1278.     /*
  1279.      * Get atoms used as property names.
  1280.      */
  1281.  
  1282.     dispPtr->commProperty = Tk_InternAtom(dispPtr->commTkwin, "Comm");
  1283.     dispPtr->registryProperty = Tk_InternAtom(dispPtr->commTkwin,
  1284.         "InterpRegistry");
  1285.     dispPtr->appNameProperty = Tk_InternAtom(dispPtr->commTkwin,
  1286.         "TK_APPLICATION");
  1287.  
  1288.     return TCL_OK;
  1289. }
  1290.  
  1291. /*
  1292.  *--------------------------------------------------------------
  1293.  *
  1294.  * SendEventProc --
  1295.  *
  1296.  *    This procedure is invoked automatically by the toolkit
  1297.  *    event manager when a property changes on the communication
  1298.  *    window.  This procedure reads the property and handles
  1299.  *    command requests and responses.
  1300.  *
  1301.  * Results:
  1302.  *    None.
  1303.  *
  1304.  * Side effects:
  1305.  *    If there are command requests in the property, they
  1306.  *    are executed.  If there are responses in the property,
  1307.  *    their information is saved for the (ostensibly waiting)
  1308.  *    "send" commands. The property is deleted.
  1309.  *
  1310.  *--------------------------------------------------------------
  1311.  */
  1312.  
  1313. static void
  1314. SendEventProc(clientData, eventPtr)
  1315.     ClientData clientData;    /* Display information. */    
  1316.     XEvent *eventPtr;        /* Information about event. */
  1317. {
  1318.     TkDisplay *dispPtr = (TkDisplay *) clientData;
  1319.     char *propInfo;
  1320.     register char *p;
  1321.     int result, actualFormat;
  1322.     unsigned long numItems, bytesAfter;
  1323.     Atom actualType;
  1324.     Tcl_Interp *remoteInterp;    /* Interp in which to execute the command. */
  1325.  
  1326.     if ((eventPtr->xproperty.atom != dispPtr->commProperty)
  1327.         || (eventPtr->xproperty.state != PropertyNewValue)) {
  1328.     return;
  1329.     }
  1330.  
  1331.     /*
  1332.      * Read the comm property and delete it.
  1333.      */
  1334.  
  1335.     propInfo = NULL;
  1336.     result = XGetWindowProperty(dispPtr->display,
  1337.         Tk_WindowId(dispPtr->commTkwin),
  1338.         dispPtr->commProperty, 0, MAX_PROP_WORDS, True,
  1339.         XA_STRING, &actualType, &actualFormat,
  1340.         &numItems, &bytesAfter, (unsigned char **) &propInfo);
  1341.  
  1342.     /*
  1343.      * If the property doesn't exist or is improperly formed
  1344.      * then ignore it.
  1345.      */
  1346.  
  1347.     if ((result != Success) || (actualType != XA_STRING)
  1348.         || (actualFormat != 8)) {
  1349.     if (propInfo != NULL) {
  1350.         XFree(propInfo);
  1351.     }
  1352.     return;
  1353.     }
  1354.  
  1355.     /*
  1356.      * Several commands and results could arrive in the property at
  1357.      * one time;  each iteration through the outer loop handles a
  1358.      * single command or result.
  1359.      */
  1360.  
  1361.     for (p = propInfo; (p-propInfo) < numItems; ) {
  1362.     /*
  1363.      * Ignore leading NULLs; each command or result starts with a
  1364.      * NULL so that no matter how badly formed a preceding command
  1365.      * is, we'll be able to tell that a new command/result is
  1366.      * starting.
  1367.      */
  1368.  
  1369.     if (*p == 0) {
  1370.         p++;
  1371.         continue;
  1372.     }
  1373.  
  1374.     if ((*p == 'c') && (p[1] == 0)) {
  1375.         Window commWindow;
  1376.         char *interpName, *script, *serial, *end;
  1377.         Tcl_DString reply;
  1378.         RegisteredInterp *riPtr;
  1379.  
  1380.         /*
  1381.          *----------------------------------------------------------
  1382.          * This is an incoming command from some other application.
  1383.          * Iterate over all of its options.  Stop when we reach
  1384.          * the end of the property or something that doesn't look
  1385.          * like an option.
  1386.          *----------------------------------------------------------
  1387.          */
  1388.  
  1389.         p += 2;
  1390.         interpName = NULL;
  1391.         commWindow = None;
  1392.         serial = "";
  1393.         script = NULL;
  1394.         while (((p-propInfo) < numItems) && (*p == '-')) {
  1395.         switch (p[1]) {
  1396.             case 'r':
  1397.             commWindow = (Window) strtoul(p+2, &end, 16);
  1398.             if ((end == p+2) || (*end != ' ')) {
  1399.                 commWindow = None;
  1400.             } else {
  1401.                 p = serial = end+1;
  1402.             }
  1403.             break;
  1404.             case 'n':
  1405.             if (p[2] == ' ') {
  1406.                 interpName = p+3;
  1407.             }
  1408.             break;
  1409.             case 's':
  1410.             if (p[2] == ' ') {
  1411.                 script = p+3;
  1412.             }
  1413.             break;
  1414.         }
  1415.         while (*p != 0) {
  1416.             p++;
  1417.         }
  1418.         p++;
  1419.         }
  1420.  
  1421.         if ((script == NULL) || (interpName == NULL)) {
  1422.         continue;
  1423.         }
  1424.  
  1425.         /*
  1426.          * Initialize the result property, so that we're ready at any
  1427.          * time if we need to return an error.
  1428.          */
  1429.  
  1430.         if (commWindow != None) {
  1431.         Tcl_DStringInit(&reply);
  1432.         Tcl_DStringAppend(&reply, "\0r\0-s ", 6);
  1433.         Tcl_DStringAppend(&reply, serial, -1);
  1434.         Tcl_DStringAppend(&reply, "\0-r ", 4);
  1435.         }
  1436.  
  1437.         if (!ServerSecure(dispPtr)) {
  1438.         if (commWindow != None) {
  1439.             Tcl_DStringAppend(&reply, "X server insecure (must use xauth-style authorization); command ignored", -1);
  1440.         }
  1441.         result = TCL_ERROR;
  1442.         goto returnResult;
  1443.         }
  1444.  
  1445.         /*
  1446.          * Locate the application, then execute the script.
  1447.          */
  1448.  
  1449.         for (riPtr = registry; ; riPtr = riPtr->nextPtr) {
  1450.         if (riPtr == NULL) {
  1451.             if (commWindow != None) {
  1452.             Tcl_DStringAppend(&reply,
  1453.                 "receiver never heard of interpreter \"", -1);
  1454.             Tcl_DStringAppend(&reply, interpName, -1);
  1455.             Tcl_DStringAppend(&reply, "\"", 1);
  1456.             }
  1457.             result = TCL_ERROR;
  1458.             goto returnResult;
  1459.         }
  1460.         if (strcmp(riPtr->name, interpName) == 0) {
  1461.             break;
  1462.         }
  1463.         }
  1464.         Tcl_Preserve((ClientData) riPtr);
  1465.  
  1466.             /*
  1467.              * We must protect the interpreter because the script may
  1468.              * enter another event loop, which might call Tcl_DeleteInterp.
  1469.              */
  1470.  
  1471.             remoteInterp = riPtr->interp;
  1472.             Tcl_Preserve((ClientData) remoteInterp);
  1473.  
  1474.             result = Tcl_GlobalEval(remoteInterp, script);
  1475.  
  1476.             /*
  1477.              * The call to Tcl_Release may have released the interpreter
  1478.              * which will cause the "send" command for that interpreter
  1479.              * to be deleted. The command deletion callback will set the
  1480.              * riPtr->interp field to NULL, hence the check below for NULL.
  1481.              */
  1482.  
  1483.         if (commWindow != None) {
  1484.         Tcl_DStringAppend(&reply, remoteInterp->result, -1);
  1485.         if (result == TCL_ERROR) {
  1486.             char *varValue;
  1487.     
  1488. #ifdef STk_CODE
  1489.             varValue = Tcl_GetVar(remoteInterp, "*error-info*",
  1490.                       TCL_GLOBAL_ONLY);
  1491. #else
  1492.             varValue = Tcl_GetVar2(remoteInterp, "errorInfo",
  1493.                 (char *) NULL, TCL_GLOBAL_ONLY);
  1494. #endif
  1495.             if (varValue != NULL) {
  1496.             Tcl_DStringAppend(&reply, "\0-i ", 4);
  1497.             Tcl_DStringAppend(&reply, varValue, -1);
  1498.             }
  1499. #ifdef STk_CODE
  1500.             varValue = Tcl_GetVar(remoteInterp, "*error-code*",
  1501.                       TCL_GLOBAL_ONLY);
  1502. #else
  1503.             varValue = Tcl_GetVar2(remoteInterp, "errorCode",
  1504.                 (char *) NULL, TCL_GLOBAL_ONLY);
  1505. #endif
  1506.             if (varValue != NULL) {
  1507.             Tcl_DStringAppend(&reply, "\0-e ", 4);
  1508.             Tcl_DStringAppend(&reply, varValue, -1);
  1509.             }
  1510.         }
  1511.         }
  1512.             Tcl_Release((ClientData) remoteInterp);
  1513.         Tcl_Release((ClientData) riPtr);
  1514.  
  1515.         /*
  1516.          * Return the result to the sender if a commWindow was
  1517.          * specified (if none was specified then this is an asynchronous
  1518.          * call).  Right now reply has everything but the completion
  1519.          * code, but it needs the NULL to terminate the current option.
  1520.          */
  1521.  
  1522.         returnResult:
  1523.         if (commWindow != None) {
  1524.         if (result != TCL_OK) {
  1525.             char buffer[20];
  1526.     
  1527.             sprintf(buffer, "%d", result);
  1528.             Tcl_DStringAppend(&reply, "\0-c ", 4);
  1529.             Tcl_DStringAppend(&reply, buffer, -1);
  1530.         }
  1531.         (void) AppendPropCarefully(dispPtr->display, commWindow,
  1532.             dispPtr->commProperty, Tcl_DStringValue(&reply),
  1533.             Tcl_DStringLength(&reply) + 1,
  1534.             (PendingCommand *) NULL);
  1535.         XFlush(dispPtr->display);
  1536.         Tcl_DStringFree(&reply);
  1537.         }
  1538.     } else if ((*p == 'r') && (p[1] == 0)) {
  1539.         int serial, code, gotSerial;
  1540.         char *errorInfo, *errorCode, *resultString;
  1541.         PendingCommand *pcPtr;
  1542.  
  1543.         /*
  1544.          *----------------------------------------------------------
  1545.          * This is a reply to some command that we sent out.  Iterate
  1546.          * over all of its options.  Stop when we reach the end of the
  1547.          * property or something that doesn't look like an option.
  1548.          *----------------------------------------------------------
  1549.          */
  1550.  
  1551.         p += 2;
  1552.         code = TCL_OK;
  1553.         gotSerial = 0;
  1554.         errorInfo = NULL;
  1555.         errorCode = NULL;
  1556.         resultString = "";
  1557.         while (((p-propInfo) < numItems) && (*p == '-')) {
  1558.         switch (p[1]) {
  1559.             case 'c':
  1560.             if (sscanf(p+2, " %d", &code) != 1) {
  1561.                 code = TCL_OK;
  1562.             }
  1563.             break;
  1564.             case 'e':
  1565.             if (p[2] == ' ') {
  1566.                 errorCode = p+3;
  1567.             }
  1568.             break;
  1569.             case 'i':
  1570.             if (p[2] == ' ') {
  1571.                 errorInfo = p+3;
  1572.             }
  1573.             break;
  1574.             case 'r':
  1575.             if (p[2] == ' ') {
  1576.                 resultString = p+3;
  1577.             }
  1578.             break;
  1579.             case 's':
  1580.             if (sscanf(p+2, " %d", &serial) == 1) {
  1581.                 gotSerial = 1;
  1582.             }
  1583.             break;
  1584.         }
  1585.         while (*p != 0) {
  1586.             p++;
  1587.         }
  1588.         p++;
  1589.         }
  1590.  
  1591.         if (!gotSerial) {
  1592.         continue;
  1593.         }
  1594.  
  1595.         /*
  1596.          * Give the result information to anyone who's
  1597.          * waiting for it.
  1598.          */
  1599.  
  1600.         for (pcPtr = pendingCommands; pcPtr != NULL;
  1601.             pcPtr = pcPtr->nextPtr) {
  1602.         if ((serial != pcPtr->serial) || (pcPtr->result != NULL)) {
  1603.             continue;
  1604.         }
  1605.         pcPtr->code = code;
  1606.         if (resultString != NULL) {
  1607.             pcPtr->result = (char *) ckalloc((unsigned)
  1608.                 (strlen(resultString) + 1));
  1609.             strcpy(pcPtr->result, resultString);
  1610.         }
  1611.         if (code == TCL_ERROR) {
  1612.             if (errorInfo != NULL) {
  1613.             pcPtr->errorInfo = (char *) ckalloc((unsigned)
  1614.                 (strlen(errorInfo) + 1));
  1615.             strcpy(pcPtr->errorInfo, errorInfo);
  1616.             }
  1617.             if (errorCode != NULL) {
  1618.             pcPtr->errorCode = (char *) ckalloc((unsigned)
  1619.                 (strlen(errorCode) + 1));
  1620.             strcpy(pcPtr->errorCode, errorCode);
  1621.             }
  1622.         }
  1623.         pcPtr->gotResponse = 1;
  1624.         break;
  1625.         }
  1626.     } else {
  1627.         /*
  1628.          * Didn't recognize this thing.  Just skip through the next
  1629.          * null character and try again.
  1630.          */
  1631.  
  1632.         while (*p != 0) {
  1633.         p++;
  1634.         }
  1635.         p++;
  1636.     }
  1637.     }
  1638.     XFree(propInfo);
  1639. }
  1640.  
  1641. /*
  1642.  *--------------------------------------------------------------
  1643.  *
  1644.  * AppendPropCarefully --
  1645.  *
  1646.  *    Append a given property to a given window, but set up
  1647.  *    an X error handler so that if the append fails this
  1648.  *    procedure can return an error code rather than having
  1649.  *    Xlib panic.
  1650.  *
  1651.  * Results:
  1652.  *    None.
  1653.  *
  1654.  * Side effects:
  1655.  *    The given property on the given window is appended to.
  1656.  *    If this operation fails and if pendingPtr is non-NULL,
  1657.  *    then the pending operation is marked as complete with
  1658.  *    an error.
  1659.  *
  1660.  *--------------------------------------------------------------
  1661.  */
  1662.  
  1663. static void
  1664. AppendPropCarefully(display, window, property, value, length, pendingPtr)
  1665.     Display *display;        /* Display on which to operate. */
  1666.     Window window;        /* Window whose property is to
  1667.                  * be modified. */
  1668.     Atom property;        /* Name of property. */
  1669.     char *value;        /* Characters to append to property. */
  1670.     int length;            /* Number of bytes to append. */
  1671.     PendingCommand *pendingPtr;    /* Pending command to mark complete
  1672.                  * if an error occurs during the
  1673.                  * property op.  NULL means just
  1674.                  * ignore the error. */
  1675. {
  1676.     Tk_ErrorHandler handler;
  1677.  
  1678.     handler = Tk_CreateErrorHandler(display, -1, -1, -1, AppendErrorProc,
  1679.     (ClientData) pendingPtr);
  1680.     XChangeProperty(display, window, property, XA_STRING, 8,
  1681.         PropModeAppend, (unsigned char *) value, length);
  1682.     Tk_DeleteErrorHandler(handler);
  1683. }
  1684.  
  1685. /*
  1686.  * The procedure below is invoked if an error occurs during
  1687.  * the XChangeProperty operation above.
  1688.  */
  1689.  
  1690.     /* ARGSUSED */
  1691. static int
  1692. AppendErrorProc(clientData, errorPtr)
  1693.     ClientData clientData;    /* Command to mark complete, or NULL. */
  1694.     XErrorEvent *errorPtr;    /* Information about error. */
  1695. {
  1696.     PendingCommand *pendingPtr = (PendingCommand *) clientData;
  1697.     register PendingCommand *pcPtr;
  1698.  
  1699.     if (pendingPtr == NULL) {
  1700.     return 0;
  1701.     }
  1702.  
  1703.     /*
  1704.      * Make sure this command is still pending.
  1705.      */
  1706.  
  1707.     for (pcPtr = pendingCommands; pcPtr != NULL;
  1708.         pcPtr = pcPtr->nextPtr) {
  1709.     if ((pcPtr == pendingPtr) && (pcPtr->result == NULL)) {
  1710.         pcPtr->result = (char *) ckalloc((unsigned)
  1711.             (strlen(pcPtr->target) + 50));
  1712.         sprintf(pcPtr->result, "no application named \"%s\"",
  1713.             pcPtr->target);
  1714.         pcPtr->code = TCL_ERROR;
  1715.         pcPtr->gotResponse = 1;
  1716.         break;
  1717.     }
  1718.     }
  1719.     return 0;
  1720. }
  1721.  
  1722. /*
  1723.  *--------------------------------------------------------------
  1724.  *
  1725.  * TimeoutProc --
  1726.  *
  1727.  *    This procedure is invoked when an unusually long amout of
  1728.  *    time has elapsed during the processing of a sent command.
  1729.  *    It checks to make sure that the target application still
  1730.  *    exists, and reschedules itself to check again later.
  1731.  *
  1732.  * Results:
  1733.  *    None.
  1734.  *
  1735.  * Side effects:
  1736.  *    If the target application has gone away abort the send
  1737.  *    operation with an error.
  1738.  *
  1739.  *--------------------------------------------------------------
  1740.  */
  1741.  
  1742. static void
  1743. TimeoutProc(clientData)
  1744.     ClientData clientData;    /* Information about command that
  1745.                  * has been sent but not yet
  1746.                  * responded to. */
  1747. {
  1748.     PendingCommand *pcPtr = (PendingCommand *) clientData;
  1749.     register PendingCommand *pcPtr2;
  1750.  
  1751.     /*
  1752.      * Make sure that the command is still in the pending list
  1753.      * and that it hasn't already completed.  Then validate the
  1754.      * existence of the target application.
  1755.      */
  1756.  
  1757.     for (pcPtr2 = pendingCommands; pcPtr2 != NULL;
  1758.         pcPtr2 = pcPtr2->nextPtr) {
  1759.     char *msg;
  1760.     if ((pcPtr2 != pcPtr) || (pcPtr2->result != NULL)) {
  1761.         continue;
  1762.     }
  1763.     if (!ValidateName(pcPtr2->dispPtr, pcPtr2->target,
  1764.         pcPtr2->commWindow, 0)) {
  1765.         if (ValidateName(pcPtr2->dispPtr, pcPtr2->target,
  1766.             pcPtr2->commWindow, 1)) {
  1767.         msg =
  1768.                     "target application died or uses a Tk version before 4.0";
  1769.         } else {
  1770.         msg = "target application died";
  1771.         }
  1772.         pcPtr2->code = TCL_ERROR;
  1773.         pcPtr2->result = (char *) ckalloc((unsigned) (strlen(msg) + 1));
  1774.         strcpy(pcPtr2->result, msg);
  1775.         pcPtr2->gotResponse = 1;
  1776.     } else {
  1777.         Tcl_DeleteModalTimeout(TimeoutProc, clientData);
  1778.         Tcl_CreateModalTimeout(2000, TimeoutProc, clientData);
  1779.     }
  1780.     }
  1781. }
  1782.  
  1783. /*
  1784.  *--------------------------------------------------------------
  1785.  *
  1786.  * DeleteProc --
  1787.  *
  1788.  *    This procedure is invoked by Tcl when the "send" command
  1789.  *    is deleted in an interpreter.  It unregisters the interpreter.
  1790.  *
  1791.  * Results:
  1792.  *    None.
  1793.  *
  1794.  * Side effects:
  1795.  *    The interpreter given by riPtr is unregistered.
  1796.  *
  1797.  *--------------------------------------------------------------
  1798.  */
  1799.  
  1800. static void
  1801. DeleteProc(clientData)
  1802.     ClientData clientData;    /* Info about registration, passed
  1803.                  * as ClientData. */
  1804. {
  1805.     RegisteredInterp *riPtr = (RegisteredInterp *) clientData;
  1806.     register RegisteredInterp *riPtr2;
  1807.     NameRegistry *regPtr;
  1808.  
  1809.     regPtr = RegOpen(riPtr->interp, riPtr->dispPtr, 1);
  1810.     RegDeleteName(regPtr, riPtr->name);
  1811.     RegClose(regPtr);
  1812.  
  1813.     if (registry == riPtr) {
  1814.     registry = riPtr->nextPtr;
  1815.     } else {
  1816.     for (riPtr2 = registry; riPtr2 != NULL;
  1817.         riPtr2 = riPtr2->nextPtr) {
  1818.         if (riPtr2->nextPtr == riPtr) {
  1819.         riPtr2->nextPtr = riPtr->nextPtr;
  1820.         break;
  1821.         }
  1822.     }
  1823.     }
  1824.     ckfree((char *) riPtr->name);
  1825.     riPtr->interp = NULL;
  1826.     UpdateCommWindow(riPtr->dispPtr);
  1827.     Tcl_EventuallyFree((ClientData) riPtr, TCL_DYNAMIC);
  1828. }
  1829.  
  1830. /*
  1831.  *----------------------------------------------------------------------
  1832.  *
  1833.  * SendRestrictProc --
  1834.  *
  1835.  *    This procedure filters incoming events when a "send" command
  1836.  *    is outstanding.  It defers all events except those containing
  1837.  *    send commands and results.
  1838.  *
  1839.  * Results:
  1840.  *    False is returned except for property-change events on the
  1841.  *    given commWindow.
  1842.  *
  1843.  * Side effects:
  1844.  *    None.
  1845.  *
  1846.  *----------------------------------------------------------------------
  1847.  */
  1848.  
  1849.     /* ARGSUSED */
  1850. static Tk_RestrictAction
  1851. SendRestrictProc(arg, eventPtr)
  1852.     ClientData arg;        /* Comunication window in which
  1853.                  * we're interested. */
  1854.     register XEvent *eventPtr;    /* Event that just arrived. */
  1855. {
  1856.     register Tk_Window comm = (Tk_Window) arg;
  1857.  
  1858.     if ((eventPtr->xany.display != Tk_Display(comm))
  1859.         || (eventPtr->type != PropertyNotify)
  1860.         || (eventPtr->xproperty.window != Tk_WindowId(comm))) {
  1861.     return TK_DEFER_EVENT;
  1862.     }
  1863.     return TK_PROCESS_EVENT;
  1864. }
  1865.  
  1866. /*
  1867.  *----------------------------------------------------------------------
  1868.  *
  1869.  * UpdateCommWindow --
  1870.  *
  1871.  *    This procedure updates the list of application names stored
  1872.  *    on our commWindow.  It is typically called when interpreters
  1873.  *    are registered and unregistered.
  1874.  *
  1875.  * Results:
  1876.  *    None.
  1877.  *
  1878.  * Side effects:
  1879.  *    The TK_APPLICATION property on the comm window is updated.
  1880.  *
  1881.  *----------------------------------------------------------------------
  1882.  */
  1883.  
  1884. static void
  1885. UpdateCommWindow(dispPtr)
  1886.     TkDisplay *dispPtr;        /* Display whose commWindow is to be
  1887.                  * updated. */
  1888. {
  1889.     Tcl_DString names;
  1890.     RegisteredInterp *riPtr;
  1891.  
  1892.     Tcl_DStringInit(&names);
  1893.     for (riPtr = registry; riPtr != NULL; riPtr = riPtr->nextPtr) {
  1894.     Tcl_DStringAppendElement(&names, riPtr->name);
  1895.     }
  1896.     XChangeProperty(dispPtr->display, Tk_WindowId(dispPtr->commTkwin),
  1897.         dispPtr->appNameProperty, XA_STRING, 8, PropModeReplace,
  1898.         (unsigned char *) Tcl_DStringValue(&names),
  1899.         Tcl_DStringLength(&names));
  1900.     Tcl_DStringFree(&names);
  1901. }
  1902.